from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

import urldb
import urldb.model
from   urldb.model.url import  *

class Base(object):
    def __init__(self, options):
        self.db = None

        # build the database connection url
        # ASSUMPTION: if the name lacks a : and / characters, assume it's just a name for a sqllite db 
        dbName = options.database
        if dbName.find(':') < 1 and dbName.find('/') < 1:
            dbName = 'sqlite:///' + options.database

        self.db = create_engine(dbName)
        self.db.echo = False
        metadata = MetaData(self.db)
        urldb.model.init(options)
        if options.create:
            print 'creating new database...'
            urldb.model.DeclarativeBase.metadata.drop_all(bind=self.db)
            urldb.model.DeclarativeBase.metadata.create_all(bind=self.db)

        self.urlTable = Url.__table__
        self.urlParamTable = UrlParam.__table__
        self.tables = [self.urlTable, self.urlParamTable]


    def get_session(self):
        Session = sessionmaker(bind=self.db)
        session = Session()
        return session

